import axios from 'axios'
import '@/api/axios'
import { getToken } from '@/utils/auth'

const xhr = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
});

/**
 * @param {object} request     封装的请求
 * @param {string} url         请求地址
 * @param {object} data        请求参数
 * @param {string} method      请求方式
 * @param {boolean} needHeader 是否需要带上登录信息 token
 * @param {boolean} getRes     是否需要获取请求所有返回信息  用于分页和获取总数
 * @param {object} param       用于修改时需要带上参数到请求路径上
*/
export const request = (url, data, method = 'GET', needHeader = false, getRes = false, param = false) => {
  let headers = {};
  if (needHeader) {
    if (getRes) {
      headers = {
        token: encodeURIComponent(getToken()),
        // Prefer: `count=exact`,
        // 'Content-Type': 'application/json;charset=utf-8'
      };
    } else {
      // headers = {
      //   token:  encodeURIComponent(getToken()),
      //   'Content-Type': 'application/json;charset=utf-8'
      // };
    }
  }
  return new Promise((resolve, reject) => {
    if (method === 'GET') {
      xhr({ url, method, data, }).then(res => {
        if (getRes) {
          resolve(res);
        } else {
          resolve(res.data);
        }
      }).catch(err => {
        reject(err)
      })
    } else {
      xhr({ url, data, method, headers, getRes, param }).then(res => {
        if (getRes) {
          resolve(res);
        } else {
          resolve(res.data);
        }
      }).catch(err => {
        reject(err)
      })
    }
  })
}

/**
 * @param {object} upload       封装上传文件请求
 * @param {string} url          请求地址
 * @param {object} file         上传文件对象
 * @param {boolean} needHeader  是否需要登录信息 token
*/
export const upload = (url, file, needHeader) => {
  let param = new FormData();
  param.append('file', file)
  if (needHeader) {
    return xhr(url, 'POST', param, {
      headers: {
        token: sessionStorage.getItem('token')
      }
    })
  } else {
    return xhr(url, 'POST', param)
  }
}